package com.yuanxin.yuanxinkit.utils;

import android.content.SharedPreferences;
import android.util.Log;

import com.facebook.react.bridge.ReactApplicationContext;
import com.yuanxin.yuanxinkit.AccountModule;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by lz on 2017/12/8.
 */

public class TokenInterceptor implements Interceptor {
    private final static String TAG = "TokenInterceptor";
    private ReactApplicationContext context;
    private AccountModule accountModule;

    public TokenInterceptor(ReactApplicationContext context, AccountModule accountModule) {
        this.context = context;
        this.accountModule = accountModule;
    }

    private static Object lock=new Object();

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Request.Builder builder = request.newBuilder();

        String token=getAccessToken();
        setAuthHeader(builder, token);

        request = builder.build();
        Response response = chain.proceed(request);
        if (isTokenExpired(response)) {
            synchronized (lock) { //perform all 401 in sync blocks, to avoid multiply token updates
                String currentToken = getAccessToken(); //get currently stored token
                if(currentToken != null && currentToken.equals(token)) { //compare current token with token that was stored before, if it was not updated - do update
                   // Log.d(TAG, "开始刷新TOKEN");
                    String newToken = accountModule.RefreshTokenSync();
                   // Log.d(TAG, "完成刷新TOKEN:" + newToken);
                    if(newToken==null){
                        //TODO：刷新失败，退出登录
                        EventBus.getDefault().post("imLogout");
                        return response;
                    }
                }

                if(getAccessToken() != null) {
                   // Log.e(TAG,"使用新token重新请求："+request.url().url().toString());
                    setAuthHeader(builder, getAccessToken());
                    request = builder.build();
                    return chain.proceed(request);
                }
            }
        }
        return response;
    }



    /**
     * 根据Response，判断Token是否失效
     *
     * @param response
     * @return
     */
    private boolean isTokenExpired(Response response) {
        if (response.code() == 401) {
            return true;
        }
        return false;
    }

    private void setAuthHeader(Request.Builder builder, String token) {
        if (token != null) //Add Auth token to each request if authorized
            builder.header("Authorization", String.format("Bearer %s", token));
    }

    private String getAccessToken(){
        SharedPreferences sp = this.context.getSharedPreferences("login", this.context.MODE_PRIVATE);
        SharedPreferences.Editor edt = sp.edit();
        String token = sp.getString("access_token", null);
        return token;
    }
}
